from django.shortcuts import render, redirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
import os, re, json,zipfile,shutil
from web import models
from backend import audit
from backend.task_manager import MultiTaskManger


# Create your views here.
@login_required
def dashboard(request):
    return render(request, 'index.html')


def acc_login(request):
    error_msg = ''
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user:
            login(request, user)
            return redirect("/")
        else:
            error_msg = "用户名或密码错误！"
    return render(request, 'login.html', {"error_msg": error_msg,
                                          })


def acc_logout(request):
    logout(request)
    return redirect("/login/")


@login_required
def user_audit(request):
    log_dirs = os.listdir(settings.AUDIT_LOG_DIR)
    return render(request, 'user_audit.html', locals())


@login_required
def aduit_log_date(request, log_date):
    log_date_path = os.path.join(settings.AUDIT_LOG_DIR, log_date)
    log_file_dir = os.listdir(log_date_path)
    session_ids = [re.search("\d+", i).group() for i in log_file_dir]
    session_objs = models.Session.objects.filter(id__in=session_ids)
    return render(request, 'user_audit_file_list.html', locals())


@login_required
def audit_log_detail(request, log_date, session_id):
    log_date_path = os.path.join(settings.AUDIT_LOG_DIR, log_date)
    log_file = "session_%s.log" % session_id
    log_file_path = os.path.join(log_date_path, log_file)

    log_parser = audit.AuditLogHandler(log_file_path)
    cmd_list = log_parser.parse()

    return render(request, "user_audit_detail.html", locals())


@login_required
def webssh(request):
    return render(request, "webssh.html")


@login_required
def multitask_cmd(request):
    return render(request, "multitask_cmd.html")


@login_required
def multitask(request):
    print("---->", request.POST)
    task_data = json.loads(request.POST.get('task_data'))
    print("----->selected hosts", task_data)

    task_obj = MultiTaskManger(request)
    selected_hosts = list(task_obj.task.tasklogdetail_set.all().values('id',
                                                                       'bind_host__host__ip_addr',
                                                                       'bind_host__host__hostname',
                                                                       'bind_host__host_user__username'))

    return HttpResponse(
        json.dumps({'task_id': task_obj.task.id, 'selected_hosts': selected_hosts})
    )


@login_required
def task_result(request):
    task_id = request.GET.get('task_id')
    task_obj = models.Task.objects.get(id=task_id)
    task_log_result = list(task_obj.tasklogdetail_set.all().values('id', 'result', 'status', 'start_date', 'end_date'))

    return HttpResponse(json.dumps(task_log_result, default=json_date_handler))


def json_date_handler(obj):
    if hasattr(obj, 'isoformat'):
        return obj.strftime("%Y-%m-%d %T")


@login_required
def multitask_file(request):
    return render(request, "multitask_file.html")



@csrf_exempt
def file_upload(request):
    print(request.FILES)
    username = str(request.user)
    upload_dir = os.path.join(settings.FILE_UPLOAD_DIR, username)
    if not os.path.isdir(upload_dir):
        os.mkdir(upload_dir)

    for k,file_obj in request.FILES.items():
        with open("%s/%s" % (upload_dir, file_obj.name), "wb") as f:
            for chunk in file_obj.chunks():
                f.write(chunk)

    zipname = "%s/%s.zip" %(settings.TMP_FILE_UPLOAD_DIR,username)
    z = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)
    startdir = upload_dir
    for dirpath, dirnames, filenames in os.walk(startdir):
        for filename in filenames:
            z.write(os.path.join(dirpath, filename))
    z.close()
    # for filename_del in os.listdir(upload_dir):
    #     filepath_del = os.path.join(upload_dir,filename_del)
    #     if os.path.isfile(filepath_del):
    #         os.remove(filepath_del)

    # task_obj = MultiTaskManger(request)
    # selected_hosts = list(task_obj.task.tasklogdetail_set.all().values('id',
    #                                                                    'bind_host__host__ip_addr',
    #                                                                    'bind_host__host__hostname',
    #                                                                    'bind_host__host_user__username'))
    #
    # return HttpResponse(
    #     json.dumps({'task_id': task_obj.task.id, 'selected_hosts': selected_hosts})
    # )

    return HttpResponse(json.dumps("success"))

